// Declaration of global objects e vars
var currentDocbox;
var currentDocboxName;
var currentSheetbox;
var currentSheetboxIndex = 1;
var currentUnitbox;
var currentUnitboxes = new Array();

var rangeexpressionsmap = {};
var expressionsmap = {};

var unitboxes = {};
unitboxes['numbers'] = {};
unitboxes['strings'] = {};
unitboxes['ranges'] = {};
unitboxes['expressions'] = {};
unitboxes['graphs'] = {};

unitboxgroups = {};

var synchros = {};
var currentTimeline;

/* ----- */

window.addEvent('domready', function() {
    new Asset.css('css/gui.css', {id: 'css'});
});

function init() {
    currentDocbox = $('docbox');
    overlay = $("overlay");
    modaldialog = $("modaldialog");
    modaldialog.addEvent("click", function(e) {
    	e.stopPropagation();
    });
    
    $('docbox_name').value = 'testdocbox';
    //loadDocbox();

    $('form_unitbox').setStyle('visibility', 'hidden');
}

function loadDocbox(dname) {

	if (dname != '')
		currentDocboxName = dname;
	else
	    currentDocboxName = $('docbox_name').value;
    var request = new Ajax('parsedocbox', {method: 'post', data:'sheet=1&name='+currentDocboxName, evalScripts:true,
        onSuccess: function() {
            if (request.response['text'] == "0") {
                alert("docbox not found");
                return false;
            }

            currentDocbox.setHTML(request.response['text']);
            var els = $$('.sheetboxtitle');
            $('sheetsbar').adopt(els);
        }, onComplete: function() {
            // eseguo il binding dei range con le funzioni che li utilizzano
            for (rangeid in unitboxes.ranges) {
                var i = 0;
                var r = {};
                var pattern = new RegExp("\\W*"+rangeid+"\\W*", "m");
                for (idf in unitboxes.expressions) {
                    // qua ci vuole una bella espressione regolare...
                    if (pattern.test(unitboxes.expressions[idf].callback.toString()) == true) {
                        r[i] = idf;
                        i++;
                    }
                }

                if (i > 0)
                    rangeexpressionsmap[rangeid] = r;
            }
            
            // eseguo il binding tra le funzioni che si utilizzano reciprocamente
            for (funcid in unitboxes.expressions) {
                var i = 0;
                var r = {};
                var pattern = new RegExp("\\W*"+funcid+"\\W*", "m");
                for (idf in unitboxes.expressions) {
                    // qua ci vuole una bella espressione regolare...
                    if (pattern.test(unitboxes.expressions[idf].callback.toString()) == true) {
                        r[i] = idf;
                        i++;
                    }
                }

                if (i > 0)
                    expressionsmap[funcid] = r;
            }
            
            closedialog();
            
            new Asset.css('docbox/' + currentDocboxName + '/' + currentDocboxName + '.css', {id: currentDocboxName + 'css'});
            
            if (!$('unitboxdocbox_name'))
                $('form_unitbox').adopt(new Element('input', {'type':'hidden', 'name':'name', 'id':'unitboxdocbox_name', 'value':String(currentDocboxName)}));
            else
                $('unitboxdocbox_name').value = currentDocboxName;
        }
    });
    request.request();
}

function setCurrentUnitbox(event, id, family) {
    event = new Event(event);
    // selezione multipla
    if (event.control && id != undefined) {
        if (currentUnitboxes.contains(event.target)) {
            currentUnitboxes.remove(event.target);
            event.target.setStyle("border", "");
            event.target.setStyle("z-index", "2");
        }
        else {
            currentUnitboxes.push(event.target);
            event.target.setStyle("border", "1px solid gold");
            event.target.setStyle("z-index", "3");
        }

        $('form_unitbox').setStyle('visibility', 'hidden');
        return;
    }
    else {
        if (currentUnitboxes.length) {
            for (i = 0; i < currentUnitboxes.length; i++) {
                currentUnitboxes[i].setStyle("border", "");
                currentUnitboxes[i].setStyle("z-index", "2");
            }
            currentUnitboxes = new Array();
        }
    }

    if (currentUnitbox != undefined) {
        currentUnitbox.domobj.setStyle("border", "");
        currentUnitbox.domobj.setStyle("z-index", "2");
    }
    
    if (id == undefined && family == undefined) {
        currentUnitbox = undefined;
        $('form_unitbox').setStyle('visibility', 'hidden');
        return;
    }
    else
        $('form_unitbox').setStyle('visibility', 'visible');

    currentUnitbox = unitboxes[family][id];
    currentUnitbox.domobj.setStyle("border", "1px solid gold");
    currentUnitbox.domobj.setStyle("z-index", "3");
    if (family == 'ranges') {
        $('rangefunctions').setStyle("display", "block");
        $('unitbox_value').disabled = true;
        $('unitbox_rangefrom').value = currentUnitbox.from;
        $('unitbox_rangeto').value = currentUnitbox.to;
        $('unitbox_rangestep').value = currentUnitbox.step;
    }
    else {
        $('rangefunctions').setStyle("display", "none");
        $('unitbox_value').disabled = false;
    }
	document.getElementById("unitbox_id").value = id;
    document.getElementById("unitbox_title").value = currentUnitbox.domobj.getProperty('title');
	document.getElementById("unitbox_class").value = currentUnitbox.class;
	document.getElementById("unitbox_type").value = currentUnitbox.type;
    document.getElementById("unitbox_type_fake").value = currentUnitbox.type;
	if (currentUnitbox.value != undefined)
        document.getElementById("unitbox_value").value = currentUnitbox.value;
    else
        document.getElementById("unitbox_value").value = '';

    if (currentUnitbox.group)
        unitboxgroups[currentUnitbox.group].highlight();
}


function setUnitbox() {
    var ub_form = $('form_unitbox');

    // update unitbox
    var request = new Ajax('updateunitbox', {method: 'post', data:ub_form.toQueryString(), evalScripts:true});
    request.request();

    // reparse docbox
    var request = new Ajax('parsedocbox', {method: 'post', data:'sheet='+currentSheetboxIndex, evalScripts:true, onSuccess: function() {
        currentDocbox.setHTML(request.response['text']);
        }
    });
    request.request();
}

function newUnitbox() {
    var ub_form = $('form_new_unitbox');
    ub_form.adopt(new Element('input', {'type':'hidden', 'name':'sheet', 'id':'sheet', 'value':currentSheetbox.getProperty('id')}));

    var request = ub_form.send({method: 'post', evalScripts:false, onComplete: function() {
        alert(this.response['text']);
        }
    });
    
    var request = new Ajax('parsedocbox', {method: 'post', data:'sheet='+currentSheetboxIndex, evalScripts:true, onSuccess: function() {
        currentDocbox.setHTML(request.response['text']);
        closedialog();
        }, onComplete: function() {
        if (request.response['text'] == "0")
            alert("Error in docbox parsing");
        }
    });
    request.request();
}

function deleteUnitbox() {
    if (confirm("Really delete current unitbox?")) {
        var request = new Ajax('deleteunitbox', {method: 'post', data:'unitbox_id='+currentUnitbox.id, evalScripts:false, onComplete: function() {
            alert(this.response['text']);
            }
        });
        request.request();

        var request = new Ajax('parsedocbox', {method: 'post', data:'sheet='+currentSheetboxIndex, evalScripts:true, onSuccess: function() {
            currentDocbox.setHTML(request.response['text']);
            }
        });
        request.request();
    }
}

function setCurrentSheetbox(sheetid) {
    var els = $$('.sheetbox');
    var i = 0;
    for (; i < els.length; i++) {
        if (els[i].getProperty('id') == sheetid) {
            currentSheetbox = els[i];
            currentSheetboxIndex = i + 1;
            $E('#'+els[i].getProperty('id'), 'title').setStyle('background-color', 'white');
            els[i].getChildren().setStyle('display', '');
        }
        else {
            $E('#'+els[i].getProperty('id'), 'title').setStyle('background-color', '#e9e9e9');
            els[i].getChildren().setStyle('display', 'none');
        }
    }
}

function insertSheetbox() {
    dialog('newsheetbox');
}

function newSheetbox() {
    var ub_form = $('form_new_sheetbox');

    ub_form.adopt(new Element('input', {'type':'hidden', 'name':'sheet', 'id':'sheet', 'value':currentSheetbox.getProperty('id')}));

    var request = ub_form.send({method: 'post', evalScripts:false, onSuccess: function() {
        currentSheetbox = this.response['text'];
        }
    });

    var request = new Ajax('parsedocbox', {method: 'post', data:'sheet='+currentSheetboxIndex, evalScripts:true, onSuccess: function() {
        currentDocbox.setHTML(request.response['text']);
        closedialog();
        }
    });
    request.request();
}

function deleteSheetbox() {
    if (confirm('Really delete this sheetbox? All the unitboxes inside will be lost...')) {
        var request = new Ajax('deletesheetbox', {method: 'post', data:'sheet='+currentSheetbox.getProperty('id'), evalScripts:true, onSuccess: function() {
            currentSheetboxIndex = currentSheetboxIndex - 1;
            }
        });
        request.request();

        var request = new Ajax('parsedocbox', {method: 'post', data:'sheet='+currentSheetboxIndex, evalScripts:true, onSuccess: function() {
            currentDocbox.setHTML(request.response['text']);
            closedialog();
            }
        });
        request.request();
    }
}

grid = false;
function viewGrid() {
    if (!grid) {
        $$('.sheetbox').setStyle('background', 'url(gui/img/background-grid.png) repeat');
        grid = true;
    }
    else {
        $$('.sheetbox').setStyle('background', '');
        grid = false;
    }
}

function loadXmlContent() {
    dialog('xmlread');

    currentDocboxName = $('docbox_name').value;
    $('xmlfilename').setHTML(currentDocboxName);
    var request = new Ajax('getxmlcontent', {method: 'post', data:'name='+currentDocboxName, evalScripts:false, onComplete: function() {$('xmlfilecontent').setHTML(request.response['text'])}});
}
